package com.tanhua.dubbo.api.mongo.impl;

import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class FriendApiImpl implements FriendApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Long userId, Long friendId) {
        Query query1 = new Query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        if(!mongoTemplate.exists(query1, Friend.class)){
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
        Query query2 = new Query(Criteria.where("userId").is(friendId).and("friendId").is(userId));
        if(!mongoTemplate.exists(query2, Friend.class)){
            Friend friend = new Friend();
            friend.setUserId(friendId);
            friend.setFriendId(userId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }


    }

    @Override
    public List<Friend> findByUserId(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        return friendList;
    }
}
